import moment from 'moment';
import path from 'path';
import appRoot from 'app-root-path';
import mySqlDump from 'mysqldump';
import configDB from '../../etc/db';
import config from '../../etc';
import log from '../log';
import * as util from '../util/index';

const fsExtra = require('fs-extra');

let isBusy;

function BackupDatabase() {
    return util.resolve().then(() => {
        const name = moment().format('YYYYMMDDHHmmss');
        const dirPath = path.join(appRoot.toString(), config.BackupDatabaseDir);
        const filePath = path.join(dirPath, `${name}.sql`);
        fsExtra.ensureDir(dirPath, (err) => {
            if (err) {
                throw err;
            }
            mySqlDump({
                host: configDB.connection.host,
                user: configDB.connection.user,
                password: configDB.connection.password,
                database: configDB.connection.database,
                dest: filePath // destination file
            }, (err) => {
                if (err) {
                    throw err;
                }
            });
        });
        return true;
    }).catch(err => {
        log.error('delFiles policy is err----', err);
        return err;
    });
}

function start() {
    if (isBusy) {
        log.info('BackupDatabase is Busy');
        return;
    }
    isBusy = 1;
    try {
        BackupDatabase()
            .then(res => {
                if (res) {
                    log.info('BackupDatabase 执行成功');
                }
            })
            .catch(err => {
                log.info('BackupDatabase 执行失败', err);
            })
            .then(() => {
                isBusy = 0;
            });
    } catch (e) {
        log.error('BackupDatabase error', e);
        isBusy = 0;
    }
}

export default start;
